package com.heima.wemedia.filter;

import com.heima.model.threadlocal.WmThreadLocalUtils;
import com.heima.model.wemedia.pojo.WmUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
@WebFilter(value = "wmTokenFilter",urlPatterns = "/*")//标记为过滤器
@Component//被spring使用
@Slf4j
public class WmTokenFilter extends GenericFilterBean {
    @Override//过滤方法
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
            //请求对象  web和网关有什么区别
        HttpServletRequest request=(HttpServletRequest)servletRequest;

        //获取userId,网关过滤器中解析token得到
        String userId = request.getHeader("userId");

        //将userId设置到局部线程变量中
        if (StringUtils.isNotBlank(userId)){

            WmUser wmUser = new WmUser();
            wmUser.setId(Integer.valueOf(userId));
            WmThreadLocalUtils.setUser(wmUser);

        }

        filterChain.doFilter(servletRequest,servletResponse);//放行

    }//成为过滤器,实现filter接口,springmvc提供抽象类,继承即可

}

//只要一进tomcat,就面对过滤器,最外层的


//拦截器是springmvc框架中的概念,进入到springmvc中,路径前,路径后,用拦截器,路径级别

//再进入controller层,dao层,用AOP拦截,拦截方法,跟路径无关,用反射,方法级别
